<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘事件</title>
    <style>
        #result{
            width: 400px;
            height: 300px;
            border:solid 1px #666;
            overflow-y: scroll;
        }
    </style>
</head>
<body>
    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component{
            //声明一个状态数据
            state = {
                msgs: []
            }

            render(){
                return <div>
                        <input type="text" onKeyDown={this.handleKeyDown}  />
                        <hr />
                        <div id="result" ref={el => this.result = el}>
                            <ul>
                                {
                                    this.state.msgs.map((item, index) => {
                                        return <li key={index}>{item}</li>
                                    })
                                }
                            </ul>
                        </div>
                    </div>
            }

            handleKeyDown = (e) => {
                // console.log(e.ctrlKey);
                //判断是否按下了回车
                if(e.keyCode === 13 && e.ctrlKey){
                    //获取表单元素的值
                    // this.result.innerHTML = e.target.value;
                    //将输入的内容压入到 state.msgs 中
                    // this.state.msgs.push(e.target.value);
                    this.setState({
                        msgs: [...this.state.msgs, e.target.value]
                    });
                    
                }
            }
            //组件完成更新
            componentDidUpdate(){
                //更新滚动距离
                this.result.scrollTo(0, this.result.scrollHeight);
            }
        }

        ReactDOM.render(<App />, document.querySelector("#root"));
    </script>
</body>
</html>